package com.boby.homecamera.fragment.client


import android.graphics.Color
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.OptIn
import androidx.core.view.isVisible
import androidx.media3.common.util.UnstableApi
import androidx.recyclerview.widget.LinearLayoutManager
import com.boby.homecamera.R
import com.boby.homecamera.activity.client.CameraClientActivity
import com.boby.homecamera.adapter.BottomSpaceDecoration
import com.boby.homecamera.adapter.VideoAdapter
import com.boby.homecamera.db.VideoEventTable
import com.boby.homecamera.db.VideoTable.Video
import com.boby.homecamera.helper.SimpleVideoPlayer
import com.boby.homecamera.net.Api
import com.boby.homecamera.util.DateUtil
import com.boby.homecamera.view.EfficientVerticalListView
import com.boby.homecamera.view.MyRecyclerView
import com.boby.homecamera.view.TimeRuleView
import com.boby.homecamera.view.TimeRuleView.TimePart
import com.boby.lib_common.BaseApplication
import com.boby.lib_common.base.BaseActivity
import com.boby.lib_common.extens.dp

import com.boby.lib_common.network.Net
import com.boby.lib_common.util.BLog
import com.loper7.date_time_picker.DateTimeConfig
import com.loper7.date_time_picker.dialog.CardDatePickerDialog
import com.loper7.date_time_picker.dialog.CardWeekPickerDialog.Companion.CARD
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale



class VideoHistoryFragment : Fragment() {
    private val TAG = "VideoHistoryFragment"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ip = arguments?.getString("ip")
        token = arguments?.getString("token")
        httpPort = arguments?.getInt("httpPort")


    }



    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.view_history_video, container, false)
    }
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initHistoryView(requireView())
    }
    companion object {
        @JvmStatic
        fun newInstance(ip: String, token: String?,httpPort:Int) = VideoHistoryFragment().apply {
            arguments = Bundle().apply {
                putString("ip", ip)
                putString("token", token)
                putInt("httpPort", httpPort)
            }
        }
    }

    private var ip: String? = null
    private var token: String? = null
    private var httpPort: Int? = null
    private lateinit var trvTime :TimeRuleView
    private lateinit var tvTime: TextView
    private lateinit var tv_date: TextView

    private lateinit var rv_video_list : EfficientVerticalListView
    private var videoItemHeight: Int = 0


    private var isFirstVisible = true  // 👈 首次显示标记位
    private val todayDate = DateUtil.getTodayStartTimeMillis()
    private var selectDate = todayDate


    override fun onResume() {
        super.onResume()

        if (isVisible && isFirstVisible) {
            isFirstVisible = false
            onFragmentFirstVisible()
        }
    }

    private fun onFragmentFirstVisible() {
        // ✅ 第一次用户真正可见
        BLog.d(TAG, "onFragmentFirstVisible：${arguments?.getString("title")}")
        loadVideoList(selectDate,System.currentTimeMillis())
    }
    private var videoPlayerTimeListener:((index:Int,contentDuration: Long,duration:Long)->Unit)? = null
    @OptIn(UnstableApi::class)
    private fun initHistoryView(rootView: View){
        rv_video_list = rootView.findViewById(R.id.rv_video_list)
        tv_date = rootView.findViewById(R.id.tv_date)
        rv_video_list.setIp(ip?:"",token?:"", httpPort!! )
        initTimeRuleView(rootView)


        videoItemHeight = getItemHeight()
        videoPlayerTimeListener =  videoPlayerTimeListener@{ index:Int,contentDuration: Long,duration:Long ->
            BLog.d(TAG,"setTimeListener index:$index,contentDuration:$contentDuration,duration:$duration")
            if(trvTime.isTouch
                || rv_video_list.isUserScroll
                || System.currentTimeMillis() - rv_video_list.lastTouchTime < 1500
                || System.currentTimeMillis() - trvTime.lastTouchTime < 1500
            ){
                return@videoPlayerTimeListener
            }
            tvTime.post {
                val itemStartTime = rv_video_list.getData().get(index).startTime!!
                val newTimeValue = itemStartTime + duration
//                val timeSecond =  getDayStartTimeSecond(if(newTimeValue < startTime) startTime else newTimeValue)
                tvTime.setText(com.boby.lib_common.util.DateUtil.formatTimeHHmmss(newTimeValue))
                trvTime.setCurrentTime(newTimeValue)
                scrollToCenter(newTimeValue,false)
            }
        }


        rv_video_list.setItemClickListener { index,item ->

            if(activity is CameraClientActivity){
                initVideoPlayList()
                (activity as CameraClientActivity).playVideoItem(index,item)
            }
        }

        rv_video_list.setOnScrollListener{ totalScrollY ->
            // index
            BaseApplication.getWorkHandler()?.post {
                seekVideo(totalScrollY)
            }
        }
        tv_date.setOnClickListener {
            if(startFileDate == -1L){
                getVideoStartFileDate()
            }else{
                showDatePicker(startFileDate)
            }

        }
        tv_date.text =  SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date(selectDate))

    }
    private fun initVideoPlayList(){

        (activity as CameraClientActivity).apply {
            if(lastPlayMsgVideo){
                setVideoPlayerTimeListener(videoPlayerTimeListener)
                if(videoList != null ){
                    setVideoList(videoList!!)
                }
            }

        }

    }
    private fun seekVideo(totalScrollY: Float) {
        val centerItemOffset = rv_video_list.getCenterItemOffset(totalScrollY)
        val index = centerItemOffset.first
        val offsetPx = centerItemOffset.second?:0f
        val offset = offsetPx/videoItemHeight
        if(index >= 0 && index < rv_video_list.getData().size){
            val item = rv_video_list.getData()[index]
            val offsetTime = (item.endTime!! - item.startTime!!) * offset

            val time = item.startTime!! + offsetTime.toLong()
            tvTime.post {
                tvTime.setText(com.boby.lib_common.util.DateUtil.formatTimeHHmmss(time))
            }

            trvTime.setCurrentTime(time)
            if(activity is CameraClientActivity){
                initVideoPlayList()
                (activity as CameraClientActivity ).seekVideo(index,offsetTime.toLong())
            }
        }
    }



    private fun initTimeRuleView(rootView: View){
        trvTime = rootView.findViewById(R.id.trv_time)
        tvTime = rootView.findViewById<TextView>(R.id.tv_time)
        trvTime.setOnTimeChangedListener(object : TimeRuleView.OnTimeChangedListener {
            override fun onTimeChanged(newTimeValue: Long, isEnd: Boolean) {
                tvTime.setText(com.boby.lib_common.util.DateUtil.formatTimeHHmmss(newTimeValue))
                scrollToCenter(newTimeValue,true)
            }
        })

    }


    @OptIn(UnstableApi::class)
    private fun scrollToCenter(currentTime:Long,isEnd: Boolean){
        val data = rv_video_list.getData()
        var findClosestTimeIndex = findClosestTimeIndex(data, currentTime)
        if(findClosestTimeIndex>-1 && findClosestTimeIndex< data.size){
            val item = data.get(findClosestTimeIndex)

            val itemHeight = videoItemHeight // 如果你知道 item 高度，或者先测量
            var timeCount = 0L
            var offset = findClosestTimeIndex * itemHeight
            if(item.startTime!! <= currentTime && item.endTime!! >= currentTime){
                timeCount = item.endTime!! - item.startTime!!
                 offset +=   (itemHeight.toFloat()/timeCount.toFloat() * (currentTime - item.startTime!!)).toInt()
//                BLog.d(TAG,"scrollToCenter offset111: $offset timeCount:$timeCount time:${currentTime - item.startTime!!}")

            }else{
                if(currentTime>item.endTime!!){
                    offset += itemHeight
                }
            }

            rv_video_list.scrollToY(offset)

            if(isEnd){
                val positionMs = currentTime - item.startTime!!
                if(activity is CameraClientActivity){
                    initVideoPlayList()
                    (activity as CameraClientActivity ).seekVideo(findClosestTimeIndex,positionMs)
                }

            }
        }

    }

    fun findClosestTimeIndex(timeList: List<Video>, targetTime: Long): Int {
        var left = 0
        var right = timeList.size - 1
        var result = -1

        while (left <= right) {
            val mid = (left + right) / 2
            if (timeList[mid].startTime!! <= targetTime) {
                result = mid       // 记录当前满足条件的最大索引
                left = mid + 1     // 继续往右找更大的
            } else {
                right = mid - 1    // 过大，往左缩小
            }
        }

        return result // 返回满足条件的最大索引（或者 -1 表示都大于目标时间）
    }

    private fun getItemHeight(): Int{

        // 屏幕宽度 - 140dp - 20dp
        val itemWidth = resources.displayMetrics.widthPixels - 160f.dp()

        return (itemWidth * 9 /16.0f + 10f.dp()).toInt()

    }

    private var startTime:Long = 0
    private var isAddBottomSpaceDecoration = false
    private fun loadVideoList(startTime:Long,endTime:Long){
        (activity as BaseActivity).showLoading("")
        Api.getVideoList(Api.getRealUrl(ip,httpPort!!),token,startTime,endTime, object : Net.CallBack<List<Video>>{
            override fun onSuccess(result: List<Video>) {
                BLog.d(TAG,"loadVideoList onSuccess: ${result.size}  ")


                if(!isAddBottomSpaceDecoration){

                    val halfRecyclerViewHeight = (rv_video_list.height/2f).toInt()

                    rv_video_list.itemHeight = videoItemHeight
                    rv_video_list.firstItemTop = halfRecyclerViewHeight
                    rv_video_list.lastItemBottom = halfRecyclerViewHeight

                    isAddBottomSpaceDecoration = true
                }


                rv_video_list.setData( result)
                this@VideoHistoryFragment.startTime = startTime
                this@VideoHistoryFragment.loadTimeRuleViewData(startTime,result)
                loadVideoAudioEvent(startTime,endTime)

            }

            override fun onError(code: Int, error: String?) {
                BLog.d(TAG,"loadVideoList onError: ${code}  $error")
                (activity as BaseActivity).hideLoading()
            }

        })
    }

    private fun loadVideoAudioEvent(startTime:Long,endTime:Long){
        val videoEvent = "1,2"
        Api.getVideoEventList(Api.getRealUrl(ip,httpPort!!),token,videoEvent,startTime,endTime, true,object : Net.CallBack<List<VideoEventTable.VideoEvent>>{
            override fun onSuccess(result: List<VideoEventTable.VideoEvent>) {
                BLog.d(TAG,"loadVideoEventList onSuccess: ${result.size}  ")
                loadVideoPersonEvent(result,startTime,endTime)
            }

            override fun onError(code: Int, error: String?) {
                BLog.d(TAG,"loadVideoList onError: ${code}  $error")
                (activity as BaseActivity).hideLoading()
            }

        })
    }
    private fun loadVideoPersonEvent(audioResult: List<VideoEventTable.VideoEvent>,startTime:Long,endTime:Long){
        val videoEvent = "4"
        Api.getVideoEventList(Api.getRealUrl(ip,httpPort!!),token,videoEvent,startTime,endTime, true,object : Net.CallBack<List<VideoEventTable.VideoEvent>>{
            override fun onSuccess(result: List<VideoEventTable.VideoEvent>) {
                BLog.d(TAG,"loadVideoEventList onSuccess: ${result.size}  ")
                loadTimeEventRuleViewData(startTime,audioResult,result)
                (activity as BaseActivity).hideLoading()
            }

            override fun onError(code: Int, error: String?) {
                BLog.d(TAG,"loadVideoList onError: ${code}  $error")
                (activity as BaseActivity).hideLoading()
            }

        })
    }

        private var videoList : List<Video>? = null
    @OptIn(UnstableApi::class)
    private fun loadTimeRuleViewData(startTime:Long,videos: List<Video>) {
        // 模拟时间段数据
        val list = ArrayList<TimePart>()
//        val maxTime = 24 * 3600
        for (video in videos) {
            val part = TimePart()
//            part.startTime = getDayStartTimeSecond(if(video.startTime!! < startTime) startTime else video.startTime)
//            part.endTime = getDayStartTimeSecond(video.endTime)
//            if(part.startTime < 0 ){
////                BLog.d(TAG,"loadTimeRuleViewData part.startTime < 0 ${part.startTime}")
//                part.startTime = 0
//            }
//            if(part.endTime > maxTime ){
//                part.endTime = maxTime
//            }
            part.startTime = video.startTime!!
            part.endTime = video.endTime!!
            list.add(part)
        }

        if(list.isNotEmpty()){
//            var maxTimeValue = list.last().startTime
//            if(maxTimeValue > maxTime){
//                maxTimeValue = maxTime
//            }
//            trvTime.setMaxTimeValue(maxTimeValue)
            trvTime.setCurrentTime(list.last().startTime)
            scrollToCenter(list.last().startTime,false)
        }
        trvTime.setStartTime(startTime)
        trvTime.setTimePartList(list)
        videoList = videos

    }

        private fun loadTimeEventRuleViewData(startTime:Long,audioDetect: List<VideoEventTable.VideoEvent>,personDetect: List<VideoEventTable.VideoEvent>){
        // 模拟时间段数据
        val audioDetectList = ArrayList<TimePart>()
        for (videoEvent in audioDetect) {
            val part = TimePart()
            part.startTime = videoEvent.startTime
            part.endTime = videoEvent.endTime
            if(videoEvent.eventType == 2){
                part.color = Color.RED  ;
            }else{
                part.color = Color.YELLOW
            }
            audioDetectList.add(part)
        }
            val personDetectList = ArrayList<TimePart>()
            for (videoEvent in personDetect) {
                val part = TimePart()
                part.startTime = videoEvent.startTime
                part.endTime = videoEvent.endTime
                part.color = Color.GREEN
                personDetectList.add(part)
            }

        trvTime.setTimeEventPartList(audioDetectList,personDetectList)
    }

    private var startFileDate = -1L

    private fun getVideoStartFileDate(){
        (activity as BaseActivity).showLoading("")
        Api.getVideoStartFileDate(Api.getRealUrl(ip,httpPort!!),token, object : Net.CallBack<Long>{
            override fun onSuccess(result: Long) {
                BLog.d(VideoEventMsgFragment.Companion.TAG,"getVideoStartFileDate onSuccess: ${result}  ")
                (activity as BaseActivity).hideLoading()
                if(result!=-1L){
                    startFileDate = DateUtil.getDayStartTimeMillis( result)
//                    startFileDate = result
                    showDatePicker(startFileDate)
                }

            }

            override fun onError(code: Int, error: String?) {
                BLog.d(VideoEventMsgFragment.Companion.TAG,"getVideoStartFileDate onError: ${code}  $error")
                (activity as BaseActivity).hideLoading()
            }

        })
    }
    private fun showDatePicker(minDate:Long){
        CardDatePickerDialog.builder(requireContext())
            .setTitle("选择日期")
            .setDisplayType(DateTimeConfig.YEAR, DateTimeConfig.MONTH, DateTimeConfig.DAY)
            .setBackGroundModel(CARD)
            .showBackNow(false)
//                .setPickerLayout(layout)
            .setDefaultTime(selectDate)
            .setMaxTime(todayDate)
            .setMinTime(minDate)
            .setWrapSelectorWheel(false)
//                .setThemeColor(color)
//                .setAssistColor(color)
//                .setDividerColor(color)
            .setChooseDateModel(DateTimeConfig.DATE_DEFAULT)
            .showDateLabel(false)
            .showFocusDateInfo(false)
            .setTouchHideable(false)
//                .setLabelText("年","月","日")
            .setOnChoose("选择"){millisecond->
//                    BLog.d(TAG,"millisecond: $millisecond ,todayDate:$todayDate")
                selectDate = millisecond
                if(millisecond == todayDate){
                    loadVideoList(selectDate,System.currentTimeMillis())
                }else{
                    loadVideoList(selectDate,millisecond + 24 * 60 * 60 * 1000)
                }
                tv_date.text =  SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(Date(selectDate))


            }
            .setOnCancel("关闭") {

            }
            .build().show()
    }
}